﻿using System.IO;
using System.Text;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Interop.Word;
using Microsoft.Win32;

namespace DeleteKeywords
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.txtKeywords.Text = "华为,Huawei,huawei,HUAWEI,HuaWei,HW,PDM,PDMC,DKBA,2012实验室,海思,IAS,团泊洼,男方工厂,九华山,九龙山,BCG,TMG";
        }

        private void Select_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true; // 允许选择多个文件
            openFileDialog.Filter = "所有文件 (*.*)|*.*"; // 设置文件过滤器，根据需要调整
            var res = openFileDialog.ShowDialog();
            if (res.Value)
            {
                txtDelWordPath.Dispatcher.Invoke(() =>
                {
                    txtDelWordPath.Text = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
                });
                lbResult.Items.Clear();
                foreach (string fileName in openFileDialog.FileNames)
                {
                    // 处理每个文件，例如显示文件名或其他操作
                    lbResult.Items.Add(System.IO.Path.GetFileName(fileName));
                }
            }
        }


        private void Delete_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var path = txtDelWordPath.Text.Trim();

            // 要替换的字典，key: 要替换的文字，value: 替换为的文字
            var replaceDic = new Dictionary<string, string>();

            // 读取关键字
            var txteywords = txtKeywords.Text.Trim().Split(",");
            foreach (var keyword in txteywords)
            {
                replaceDic.Add(keyword, "DULING");
            }

            var str = new StringBuilder();
            foreach (var item in lbResult.Items)
            {
                try
                {
                    // 获取后缀，根据后缀来选择处理方式
                    var suffix = item.ToString().Split('.').Last();
                    if (suffix == "pptx" || suffix == "ppt")
                    {
                        ReplaceKeywordsInPPT($"{path}\\{item.ToString()}", replaceDic);
                    }
                    else if (suffix == "docx" || suffix == "doc")
                    {
                        ReplaceKeywordsInWord($"{path}\\{item.ToString()}", replaceDic);
                    }
                    else if (suffix == "xlsx" || suffix == "xls")
                    {
                        var res = ReplaceKeywordsInExcel($"{path}\\{item.ToString()}", replaceDic);
                        str.AppendLine($"{item.ToString()}：{res}个");
                    }
                    else if (suffix == "pdf")
                    {

                    }
                    else if (suffix == "config" || suffix == "service" || suffix == "txt" || suffix == "md" || suffix == "log" || suffix == "log" || suffix == "xml" || suffix == "json" || suffix == "html" || suffix == "htm" || suffix == "js" || suffix == "css" || suffix == "java" || suffix == "c" || suffix == "cpp" || suffix == "h" || suffix == "hpp" || suffix == "py" || suffix == "sh" || suffix == "bat" || suffix == "ini" || suffix == "conf" || suffix == "properties" || suffix == "cfg" || suffix == "yaml" || suffix == "yml" || suffix == "sql" || suffix == "json")
                    {
                        var res = ReplaceKeywordsInTxt($"{path}\\{item.ToString()}", replaceDic);
                        str.AppendLine($"{item.ToString()}：{res}个");
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("不支持的文件类型：" + $"{path}\\{item.ToString()}");
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show("发生错误：" + ex.Message);
                }
            }

            System.Windows.MessageBox.Show($"完成替换:{str.ToString()}");
        }

        /// <summary>
        /// 替换Txt文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="keywords"></param>
        public int ReplaceKeywordsInTxt(string filePath, Dictionary<string, string> keywords)
        {
            int count = 0;
            try
            {
                // 读取文件内容
                string fileContent = File.ReadAllText(filePath);
                
                // 替换文本
                foreach (var keyword in keywords)
                {
                    if (fileContent.Contains(keyword.Key))
                    {
                        count++;
                        fileContent = fileContent.Replace(keyword.Key, keyword.Value);
                    }
                }
                // 写回文件
                File.WriteAllText(filePath, fileContent);
            }
            catch (Exception ex)
            {
                throw new Exception("ReplaceKeywordsInTxt:" + ex.Message);
            }
            return count;
        }

        /// <summary>
        /// 替换PPT关键字
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="keywords"></param>
        public void ReplaceKeywordsInPPT(string filePath, Dictionary<string, string> keywords)
        {
            Microsoft.Office.Interop.PowerPoint.Application wordApp = null;
            Presentation offlic = null;

            try
            {
                wordApp = new Microsoft.Office.Interop.PowerPoint.Application();
                // 如果需要可以看到Word应用程序
                offlic = wordApp.Presentations.Open(filePath);

                foreach (Slide slide in offlic.Slides)
                {
                    // 遍历幻灯片中的每个形状
                    foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
                    {
                        // 替换形状文本中的关键字
                        if (shape.HasTextFrame == MsoTriState.msoTrue)
                        {
                            if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                            {
                                foreach (KeyValuePair<string, string> keyword in keywords)
                                {
                                    shape.TextFrame.TextRange.Text = shape.TextFrame.TextRange.Text.Replace(keyword.Key, keyword.Value);
                                }
                            }
                        }
                    }

                }
                offlic.SaveAs(filePath);
                offlic.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("ReplaceKeywordsInPPT:" + ex.Message);
            }
            finally
            {
                if (wordApp != null)
                {
                    wordApp.Quit(); // 退出PowerPoint应用程序
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                }
                // 释放对象
                if (offlic != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(offlic);
                }

            }
        }

        /// <summary>
        /// 替换Word关键字
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="keywords"></param>
        public void ReplaceKeywordsInWord(string filePath, Dictionary<string, string> keywords)
        {
            Microsoft.Office.Interop.Word.Application wordApp = null;
            Microsoft.Office.Interop.Word.Document offlic = null;

            try
            {
                wordApp = new Microsoft.Office.Interop.Word.Application();
                // 如果需要可以看到Word应用程序
                wordApp.Visible = false;
                offlic = wordApp.Documents.Open(filePath);

                foreach (KeyValuePair<string, string> keyword in keywords)
                {
                    object findText = keyword.Key;
                    object replaceText = keyword.Value;
                    object missing = Type.Missing;
                    object replaceAll = WdReplace.wdReplaceAll;

                    // 方法一
                    offlic.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
                    offlic.Content.Find.Execute(
                         ref findText, ref missing,
                         ref missing, ref missing,
                         ref missing, ref missing,
                         ref missing, ref missing, ref missing,
                         ref replaceText, ref replaceAll,
                         ref missing, ref missing,
                         ref missing, ref missing);

                    // 方法二
                    //wordApp.Selection.Find.Replacement.ClearFormatting();
                    //wordApp.Selection.Find.Replacement.Text = keyword.Value;
                    //wordApp.Selection.Find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);
                }

                offlic.Save();
                offlic.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("ReplaceKeywordsInWord:" + ex.Message);
            }
            finally
            {
                if (wordApp != null)
                {
                    wordApp.Quit(); // 退出PowerPoint应用程序
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                }
                // 释放对象
                if (offlic != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(offlic);
                }
            }
        }

        /// <summary>
        /// 替换Excel关键字
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="keywords"></param>
        public int ReplaceKeywordsInExcel(string filePath, Dictionary<string, string> keywords)
        {
            Microsoft.Office.Interop.Excel.Application wordApp = null;
            Microsoft.Office.Interop.Excel.Workbook offlic = null;
            Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
            int count = 0;
            try
            {

                wordApp = new Microsoft.Office.Interop.Excel.Application();
                // 如果需要可以看到Word应用程序
                wordApp.Visible = false;
                offlic = wordApp.Workbooks.Open(filePath);

                // 遍历所有工作表
                foreach (Microsoft.Office.Interop.Excel.Worksheet wsheet in offlic.Worksheets)
                {
                    worksheet = wsheet;
                    // 遍历所有单元格
                    for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row)
                    {
                        for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col)
                        {
                            Microsoft.Office.Interop.Excel.Range range = worksheet.Cells[row, col] as Microsoft.Office.Interop.Excel.Range;
                            if (range != null && range.Value2 != null)
                            {
                                foreach (KeyValuePair<string, string> keyword in keywords)
                                {
                                    if (keyword.Key == range.Value2.ToString())
                                    {
                                        count++;
                                        range.Value2 = keyword.Value;
                                    }
                                }
                            }
                        }
                    }
                }

                if (count > 0)
                {
                    // 关闭文档并退出Word应用程序
                    offlic.Save();
                    offlic.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ReplaceKeywordsInExcel:" + ex.Message);
            }
            finally
            {
                // 释放对象
                if (worksheet != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
                }
                if (offlic != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(offlic);
                }
                if (wordApp != null)
                {
                    wordApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                }
            }
            return count;
        }
    }
}